//
//  NRWCarTemplateShareVC.m
//  New_Runway
//
//  Created by 邢毅 on 2018/5/30.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "NRWCarTemplateShareVC.h"
#import "NRWCarTemplateShareCell.h"
#import "NRWCarShareTemplateManager.h"
#import "NRWTemplateAlertView.h"
#import "NRWCarSharePictureModel.h"
//#import "NRWCarListsModel.h"
#import "NRWShareTemplateView.h"
#import "HUPhotoBrowser.h"

@interface NRWCarTemplateShareVC ()<UICollectionViewDelegate, UICollectionViewDataSource, NRWTemplateAlertViewDelegate>

@end

@implementation NRWCarTemplateShareVC
{
    UICollectionView *_collection;
    NSArray <NRWCarSharePictureModel *>*_needTemplateImageModelArr; /**< 需要生成模板的图片模型数组 */
    NSArray <UIImage *>*_templateImageArr; /**< 模板图片数组 */
    NSString *_shortUrl; /**< 单车分享时生成的短连接 */
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [SVProgressHUD show];
    
    [self filterCarImageArr];
    
    [self loadShortUrl];
    
    [self setup];
    
    [self getTemplateImage];
}

#pragma mark - setup
- (void)setup {
    
    [self setupNavigation];
    
    [self setupCollection];
}

- (void)setupNavigation {
    
    self.navigationBarView.titleLabel.text = @"模板分享";
    [self.navigationBarView.rightItem setTitle:@"去分享" forState:UIControlStateNormal];
}

- (void)setupCollection {
    
    CGFloat itemWidth = (Screen_width - 40) / 3;
    CGFloat itemHeight = itemWidth * 1.784;
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(itemWidth, itemHeight);
    flowLayout.minimumLineSpacing = 10;
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    _collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.navH, Screen_width, Screen_height - self.navH) collectionViewLayout:flowLayout];
    _collection.backgroundColor = MAIN_BACKGROUND_COLOR();
    _collection.delegate = self;
    _collection.dataSource = self;
    [_collection registerClass:NRWCarTemplateShareCell.class forCellWithReuseIdentifier:@"cell"];
    _collection.contentInset = UIEdgeInsetsMake(14, 10, 14, 10);
    [self.view addSubview:_collection];
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return _templateImageArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    NRWCarTemplateShareCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.image = _templateImageArr[indexPath.item];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [HUPhotoBrowser showFromImageView:nil withImages:_templateImageArr atIndex:indexPath.item];
}

#pragma mark - loadShortUrl
- (void)loadShortUrl {
    
    if (self.carCount == 1) {
        
        Result *model = _needTemplateImageModelArr.firstObject.CarModel;
        
        [YQNetworking postWithUrl:@"http://api.t.sina.com.cn/short_url/shorten.json" refreshRequest:NO cache:NO params:@{@"source": @"3271760578", @"url_long": [NSString getShareCarDetailUrlWithMarketId:model.marketId shopId:model.shopId carId:model.carId]} progressBlock:nil successBlock:^(id response) {

            if (isArrayClass(response)) {
                if (isDictionaryClass([response firstObject])) {
                    _shortUrl = [response firstObject][@"url_short"];
                }
            }
        } failBlock:^(NSError *error) {

            [ShowMessage showHintMessage:@"车辆链接生成失败, 请稍后再试" duration:1.5 withRemindId:remindWarning];
        }];
    }
}

#pragma mark - NRWTemplateAlertViewDelegate
- (void)templateAlertView:(NRWTemplateAlertView *)view copyDidClick:(UIButton *)sender {
    
    [view dismiss];
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = view.contentText;
    
    [self showShareViewController];
}

- (void)templateAlertView:(NRWTemplateAlertView *)view notCopyDidClick:(UIButton *)sender {
    
    [view dismiss];
    
    [self showShareViewController];
}

- (void)templateAlertView:(NRWTemplateAlertView *)view closeBtnDidClick:(UIButton *)sender {
    
    [view dismiss];
}

#pragma mark - 把图片模型数组中的车辆图片拿出来
- (void)filterCarImageArr {
    
    NSMutableArray *arrM = [NSMutableArray array];
    
    for (NRWCarSharePictureModel *model in self.imageModelArr) {
        
        if (self.carCount == 1) {//单车分享, 所有图片参与生成模板
            
            if (model.imageType != SharePictureTypeCode) {//除了二维码都参与模板生成
                [arrM addObject:model];
            }
        } else {//多车分享, 只有车辆图片参与生成模板
            
            if (model.imageType == SharePictureTypeCar) {
                
                [arrM addObject:model];
            }
        }
        
    }
    _needTemplateImageModelArr = arrM.copy;
}

#pragma mark - getTemplateImage
- (void)getTemplateImage {
    
    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:_needTemplateImageModelArr.count];
    
    dispatch_queue_t queue = dispatch_queue_create("com.nrw.erp.getTemplateView", DISPATCH_QUEUE_SERIAL);
    
    dispatch_async(queue, ^{
 
        for (NSInteger i = 0; i < _needTemplateImageModelArr.count; i++) {
            
            NRWShareTemplateView *view = [[NRWShareTemplateView alloc] init];
            view.carImage = _needTemplateImageModelArr[i].picture;
            
            if (self.carCount == 1) {//单车分享
                view.resultModel = _needTemplateImageModelArr.firstObject.CarModel;
            } else {
                view.resultModel = _needTemplateImageModelArr[i].CarModel;
            }
            
            [arrM addObject:[NRWCarShareTemplateManager getViewScreenshots:view]];
        }
        
        _templateImageArr = arrM.copy;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [SVProgressHUD dismiss];
            [_collection reloadData];
        });
    });
}

#pragma mark - rightItemClick
- (void)rightItemClick {
  
    NRWTemplateAlertView *alertView = [[NRWTemplateAlertView alloc] init];
    alertView.delegate = self;
    [alertView show];
    
    Result *carModel = _needTemplateImageModelArr.firstObject.CarModel;
    alertView.contentText = [NRWCarShareTemplateManager getShareTextWithCarTitle:carModel.carTitle carPrice:carModel.carRetailPrice carLicenceDate:carModel.carLicenceDate carLicenceState:carModel.carLicenceState carMileage:carModel.carMileage shortUrl:_shortUrl carCount:self.carCount];
}

#pragma mark - 展示分享弹框
- (void)showShareViewController {
    
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:_templateImageArr applicationActivities:nil];
    
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (activityError) {
            [ShowMessage showHintMessage:@"分享出错, 请稍后再试" duration:1.5 withRemindId:remindWarning];
        }
    };
    
    NSMutableArray *arrM = @[UIActivityTypePostToFacebook,
                             UIActivityTypePostToTwitter,
                             UIActivityTypePostToWeibo,
                             UIActivityTypeMessage,
                             UIActivityTypeMail,
                             UIActivityTypePrint,
                             UIActivityTypeCopyToPasteboard,
                             UIActivityTypeAssignToContact,
                             UIActivityTypeSaveToCameraRoll,
                             UIActivityTypeAddToReadingList,
                             UIActivityTypePostToFlickr,
                             UIActivityTypePostToVimeo,
                             UIActivityTypePostToTencentWeibo,
                             UIActivityTypeAirDrop].mutableCopy;
    if (@available(iOS 9.0, *)) {
        [arrM addObject:UIActivityTypeOpenInIBooks];
    }
    
    if (@available(iOS 11.0, *)) {
        [arrM addObject:UIActivityTypeMarkupAsPDF];
    }
    
    activityVC.excludedActivityTypes = arrM.copy;
    [self presentViewController:activityVC animated:YES completion:nil];
}

@end
